//
//  GoodManagerModifyVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/9/22.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "GoodManagerModifyVC.h"
#import "GoodManagerAddChooseTypeCell.h"
#import "GoodManagerGoodMainModel.h"
#import "DriverAddCell.h"
#import "DriverAddInPutCell.h"

@interface GoodManagerModifyVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) NSMutableArray <GoodManagerGoodTypeModel *>*type1Array;//一级类型
@property (nonatomic, strong) NSMutableArray <GoodManagerGoodTypeModel *>*type2Array;//二级类型
@property (nonatomic, strong) NSMutableArray <GoodManagerGoodUnitModel *>*unitArray;//计量单位
@property (nonatomic, strong) NSMutableArray <GoodManagerGoodShuXingModel *>*shuXingArray;//附加属性
@property (nonatomic, strong) GoodManagerGoodMainModel *goodModel;
@property (nonatomic, strong) GoodManagerGoodTypeModel *type1Model;//选中的一级类型
@property (nonatomic, strong) GoodManagerGoodTypeModel *type2Model;//选中的二级类型
@property (nonatomic, strong) GoodManagerGoodUnitModel *unitModel;//选中的计量单位

@end

@implementation GoodManagerModifyVC

-(GoodManagerGoodUnitModel *)unitModel {
    if (!_unitModel) {
        _unitModel = [GoodManagerGoodUnitModel new];
    }
    return _unitModel;
}

- (GoodManagerGoodTypeModel *)type1Model {
    if (!_type1Model) {
        _type1Model = [GoodManagerGoodTypeModel new];
    }
    return _type1Model;
}

- (GoodManagerGoodTypeModel *)type2Model {
    if (!_type2Model) {
        _type2Model = [GoodManagerGoodTypeModel new];
    }
    return _type2Model;
}

-(GoodManagerGoodMainModel *)goodModel {
    if (!_goodModel) {
        _goodModel = [GoodManagerGoodMainModel new];
    }
    return _goodModel;
}

-(NSMutableArray *)type1Array {
    if (!_type1Array) {
        _type1Array = [NSMutableArray array];
    }
    return _type1Array;
}

-(NSMutableArray *)type2Array {
    if (!_type2Array) {
        _type2Array = [NSMutableArray array];
    }
    return _type2Array;
}

-(NSMutableArray *)unitArray {
    if (!_unitArray) {
        _unitArray = [NSMutableArray array];
    }
    return _unitArray;
}

-(NSMutableArray *)shuXingArray {
    if (!_shuXingArray) {
        _shuXingArray = [NSMutableArray array];
    }
    return _shuXingArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"保存" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)saveClick {
    [self requestForSave];
}

- (void)requestForSave {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (!self.type1Model.p_id.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择一级类型"];
        return;
    }
    
    if (!self.type2Model.p_id.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择二级类型"];
        return;
    }else {
        [dic setObject:[NSString stringWithFormat:@"%@,%@",self.type1Model.p_id,self.type2Model.p_id] forKey:@"p_id"];
        [dic setObject:[NSString stringWithFormat:@"%@-%@",self.type1Model.p_name,self.type2Model.p_name] forKey:@"p_id_name"];
    }
    if (self.goodModel.num.length) {
        [dic setObject:self.goodModel.num forKey:@"num"];
    }
    if (!self.goodModel.name.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写货物名称"];
        return;
    }else {
        [dic setObject:self.goodModel.name forKey:@"name"];
    }
    if (!self.goodModel.price.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写货物单价"];
        return;
    }else {
        [dic setObject:self.goodModel.price forKey:@"price"];
    }
    if (!self.goodModel.specs.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写货物规格"];
        return;
    }else {
        [dic setObject:self.goodModel.specs forKey:@"specs"];
    }
    if (!self.unitModel.p_id.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择计量单位"];
        return;
    }else {
        [dic setObject:self.unitModel.p_id forKey:@"measurement"];
        [dic setObject:self.unitModel.p_name forKey:@"measurement_name"];
    }
    if (!self.goodModel.weight.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写货物重量"];
        return;
    }else {
        [dic setObject:self.goodModel.weight forKey:@"weight"];
    }
    if (self.goodModel.remarks.length) {
        [dic setObject:self.goodModel.remarks forKey:@"remarks"];
    }
    NSMutableArray *mut = [NSMutableArray array];
    [self.shuXingArray enumerateObjectsUsingBlock:^(GoodManagerGoodShuXingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.status isEqualToString:@"1"]) {
            if (!obj.input_value.length) {
                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:[NSString stringWithFormat:@"请填写%@",obj.name]];
                return;
            }
        }
//        if (obj.input_value.length) {
            [mut addObject:obj.mj_keyValues];
//        }
    }];
    if (mut.count) {
        [dic setObject:[FactoryMethod toJSONString:mut] forKey:@"models"];
    }
    [dic setObject:self.Id forKey:@"good_id"];
    [dic setObject:self.goodModel.pro_num forKey:@"product_sn"];
    
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerModifyGood params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"保存成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshGoodManagerList object:nil];
            }];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑货物";
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self requestForEditInfo];
    [self requestForType1];
}

- (void)requestForEditInfo {
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerGetEditGoodInfo params:@{@"id":self.Id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.goodModel = [GoodManagerGoodMainModel mj_objectWithKeyValues:responseObject];
            self.shuXingArray = self.goodModel.model;
            NSArray *p_id_array = [NSArray array];
            if ([self.goodModel.p_id containsString:@","]) {
                p_id_array = [self.goodModel.p_id componentsSeparatedByString:@","];
            }
            NSArray *p_id_name_array = [NSArray array];
            if ([self.goodModel.p_id_name containsString:@"-"]) {
                p_id_name_array = [self.goodModel.p_id_name componentsSeparatedByString:@"-"];
            }
            self.type1Model.p_id = p_id_array.firstObject;
            self.type2Model.p_id = p_id_array.lastObject;
            [self requestForType2WithP_ID:self.type1Model.p_id];
            self.type1Model.p_name = p_id_name_array.firstObject;
            self.type2Model.p_name = p_id_name_array.lastObject;
            self.unitModel.p_id = self.goodModel.measurement;
            self.unitModel.p_name = self.goodModel.measurement_name;
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForType1 {
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerTypeList params:@{@"typeid":@(1)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.type1Array = [GoodManagerGoodTypeModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"product_type"]];
            self.unitArray = [GoodManagerGoodUnitModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"measure_type"]];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForType2WithP_ID:(NSString *)p_id {
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerTypeList params:@{@"typeid":@(2),@"p_id":p_id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.type2Array = [GoodManagerGoodTypeModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"product_type"]];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestForShuXingWithP_ID:(NSString *)p_id {
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerShuXingList params:@{@"p_id":p_id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.shuXingArray = [GoodManagerGoodShuXingModel mj_objectArrayWithKeyValuesArray:responseObject];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 8;
    }
    return self.shuXingArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            GoodManagerAddChooseTypeCell *cell = [GoodManagerAddChooseTypeCell GoodManagerAddChooseTypeCellWithTableView:tableView];
            cell.titleText = @"货物类型";
            cell.content1Text = self.type1Model.p_name ? self.type1Model.p_name : @"";
            cell.content2Text = self.type2Model.p_name ? self.type2Model.p_name : @"";
            cell.showLine = YES;
            __weak_self;
            cell.click1Block = ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                [weakself.type1Array enumerateObjectsUsingBlock:^(GoodManagerGoodTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.p_name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        weakself.type1Model = obj;
                        [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        [weakself requestForType2WithP_ID:obj.p_id];
                    }];
                    [alert addAction:action1];
                }];
                UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:cancle];
                [weakself presentViewController:alert animated:YES completion:nil];
            };
            cell.click2Block = ^{
                if (weakself.type1Model.p_name) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                    [weakself.type2Array enumerateObjectsUsingBlock:^(GoodManagerGoodTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.p_name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            weakself.type2Model = obj;
                            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            [weakself requestForShuXingWithP_ID:obj.p_id];
                        }];
                        [alert addAction:action1];
                    }];
                    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancle];
                    [weakself presentViewController:alert animated:YES completion:nil];
                }else {
                    [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"请先选择一级类型"];
                }
            };
            return cell;
        }else if (indexPath.row == 7) {
            DriverAddInPutCell *cell = [DriverAddInPutCell DriverAddInPutCellWithTableView:tableView];
            cell.contentText = self.goodModel.remarks;
            __weak_self;
            cell.remarkBlock = ^(NSString * _Nonnull str) {
                weakself.goodModel.remarks = str;
            };
            return cell;
        }else {
            DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
            if (indexPath.row == 1) {
                cell.titleText = @"原始编号";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = NO;
                cell.contentText = self.goodModel.num ? self.goodModel.num : @"";
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.goodModel.num = str;
                };
                return cell;
            }else if (indexPath.row == 2) {
                cell.titleText = @"货物名称";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.goodModel.name ? self.goodModel.name : @"";
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.goodModel.name = str;
                };
                return cell;
            }else if (indexPath.row == 3) {
                cell.titleText = @"货物单价(元)";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.goodModel.price ? self.goodModel.price : @"";
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.goodModel.price = str;
                };
                return cell;
            }else if (indexPath.row == 4) {
                cell.titleText = @"规格";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.goodModel.specs ? self.goodModel.specs : @"";
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.goodModel.specs = str;
                };
                return cell;
            }else if (indexPath.row == 5) {
                cell.titleText = @"计量单位";
                cell.showLine = YES;
                cell.canClick = YES;
                cell.isMust = YES;
                cell.contentText = self.unitModel.p_name ? self.unitModel.p_name : @"";
                __weak_self;
                cell.clickBlock = ^{
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                    [weakself.unitArray enumerateObjectsUsingBlock:^(GoodManagerGoodUnitModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.p_name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            weakself.unitModel = obj;
                            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        }];
                        [alert addAction:action1];
                    }];
                    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancle];
                    [weakself presentViewController:alert animated:YES completion:nil];
                };
                return cell;
            }else if (indexPath.row == 6) {
                cell.titleText = @"重量(kg)";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.goodModel.weight ? self.goodModel.weight : @"";
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.goodModel.weight = str;
                };
                return cell;
            }
        }
    }else {
        DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
        GoodManagerGoodShuXingModel *model = self.shuXingArray[indexPath.row];
        cell.titleText = [NSString stringWithFormat:@"%@(%@)",model.name,model.value];
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = [model.status isEqualToString:@"1"] ? YES : NO;
        cell.contentText = model.input_value ? model.input_value : @"";
        cell.cellBlock = ^(NSString * _Nonnull str) {
            model.input_value = str;
        };
        return cell;
    }
    return [UITableViewCell new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            GoodManagerAddChooseTypeCell *cell = [GoodManagerAddChooseTypeCell GoodManagerAddChooseTypeCellWithTableView:tableView];
            return cell.height;
        }else if (indexPath.row == 7) {
            DriverAddInPutCell *cell = [DriverAddInPutCell DriverAddInPutCellWithTableView:tableView];
            return cell.height;
        }else {
            DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
            return cell.height;
        }
    }else {
        DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
        return cell.height;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 45)];
    view.backgroundColor = Color_backgroundColor;
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(15, 25, ScreenW - 30, 15)];
    lab.textColor = HexColor(0x9C9DB3);
    lab.font = [UIFont systemFontOfSize:14];
    if (section == 0) {
        lab.text = @"基础信息";
    }else if (section == 1) {
        lab.text = @"附加属性";
        if (!self.shuXingArray.count) {
            return [UIView new];
        }
    }
    [view addSubview:lab];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        if (!self.shuXingArray.count) {
            return 0;
        }
    }
    return 45;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 10;
    }
    return 0;
}

@end
